import os,sys,cv2
from ai.utils.get import CMGetImages
import numpy as np

class FaceDetection:
	def __init__(self):
		self.confpath = "F:/jmd/opencv/sources/data"
		self.haarfile = "haarcascades/haarcascade_frontalface_alt2.xml"
		self.detecthandle = cv2.CascadeClassifier(self.confpath + "/" + self.haarfile)

	def detect(self, img):
		objs = self.detecthandle.detectMultiScale(img, 1.1, 4, 0,
			(30,30))
		return objs

class FaceDetectionVideo(FaceDetection):

	def __init__(self):
		FaceDetection.__init__(self)
		self.img_size = 200
		self.get = CMGetImages()

	def start(self):
		cam = cv2.VideoCapture(0)
		cv2.namedWindow("fd")
		while cam.isOpened():
			flag, frame = cam.read()
			if flag == True:
				img = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
				objs = self.detect(img)
				for rct in objs:
					ROI = img[rct[0]:rct[0]+rct[2], rct[1]:rct[1]+rct[3]]
					ROI = cv2.resize(ROI, (self.img_size, self.img_size), interpolation=cv2.INTER_LINEAR)
					params = self.model.predict(ROI) 
					print("Label %s, Confidence %.2f" % (params[0], params[1]))
					cv2.putText(frame, self.dirlist[params[0]], (rct[0], rct[1] - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)  #显示名字
					cv2.rectangle(frame, (rct[0], rct[1]), (rct[0] + rct[2], rct[1] + rct[3]),
						(0, 0, 255), 2)
				cv2.imshow("fd", frame)
				if (cv2.waitKey(10) == 27):
					cam.release()
					break
		cv2.destroyWindow("fd")

	def load_model(self, path):
		print("load model start with path ", path)

		self.dirlist = []
		for sub in os.listdir(path):
			self.dirlist.append(sub)

		[x, y] = self.get.read_images(path)
		y = np.asarray(y, dtype = np.int32)

		self.model = cv2.face.EigenFaceRecognizer_create()
		self.model.train(np.asarray(x), np.asarray(y))
		print("load model done.")

class FaceDetectionImage(FaceDetection):
	def __init__(self):
		self.basepath = "J:/av/"
		FaceDetection.__init__(self)

	def start(self, name):
		path = self.basepath + name
		img = cv2.imread(path)
		toimg = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
		objs = self.detect(img)
		for rct in objs:
			cv2.rectangle(img,  (rct[0], rct[1]), (rct[0] + rct[2], rct[1] + rct[3]), (0, 0, 255))
		cv2.imshow("fd", img)
		cv2.waitKey()

if __name__ == "__main__":
	fdv = FaceDetectionVideo()
	fdv.load_model("E:/dev/ai/dataset")
	fdv.start()
	# fdimg = FaceDetectionImage()
	# fdimg.start("1.jpg")
